package com.example.oms.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.oms.utils.DataResult;
import com.example.oms.utils.JwtUtil;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        System.out.println("初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/html;charset=utf-8");

        String url = request.getRequestURL().toString();
        System.out.println(url);

        if(url.contains("pic") || url.contains("user")|| url.contains("patient")|| url.contains("test")|| url.contains("cashier")|| url.contains("Prescription")|| url.contains("drugManagement")||url.contains("doc")){
            filterChain.doFilter(request,response);
            return;
        }

        String jwt = request.getHeader("token");

        //判断jwt是否为空
        if(!StringUtils.hasLength(jwt)){
            DataResult dataResult = new DataResult(201,"","登录效验失败，无token");
            //手动转json
            String notLogin = JSONObject.toJSONString(dataResult);
            response.getWriter().write(notLogin);
            return;
        }
        //解析jwt
        try {
            JwtUtil.ParseJwt(jwt);
        }
        catch (Exception e){
            DataResult dataResult = new DataResult(202,"","登录效验失败，token无效");
            //手动转json
            String notLogin = JSONObject.toJSONString(dataResult);
            response.getWriter().write(notLogin);
            return;
        }
        //放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        System.out.println("销毁");
    }
}
